/**
 * 主题工具函数
 * 提供便捷的主题相关工具方法
 */

// 颜色工具函数
export class ThemeUtils {
  /**
   * 将十六进制颜色转换为RGB
   */
  static hexToRgb(hex: string): { r: number; g: number; b: number } | null {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  }

  /**
   * 将RGB颜色转换为十六进制
   */
  static rgbToHex(r: number, g: number, b: number): string {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
  }

  /**
   * 调整颜色亮度
   */
  static adjustBrightness(hex: string, percent: number): string {
    const rgb = this.hexToRgb(hex)
    if (!rgb) return hex

    const adjust = (color: number) => {
      const adjusted = Math.round(color * (1 + percent / 100))
      return Math.max(0, Math.min(255, adjusted))
    }

    return this.rgbToHex(
      adjust(rgb.r),
      adjust(rgb.g),
      adjust(rgb.b)
    )
  }

  /**
   * 生成颜色色阶
   */
  static generateColorScale(baseColor: string): Record<string, string> {
    const scales = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]
    const result: Record<string, string> = {}

    scales.forEach((scale, index) => {
      let brightness: number
      if (scale <= 500) {
        // 浅色：从 +80% 到 0%
        brightness = 80 - (index * 16)
      } else {
        // 深色：从 -20% 到 -80%
        brightness = -20 - ((index - 5) * 12)
      }
      
      result[scale.toString()] = this.adjustBrightness(baseColor, brightness)
    })

    return result
  }

  /**
   * 检查颜色对比度是否符合可访问性标准
   */
  static getContrastRatio(color1: string, color2: string): number {
    const getLuminance = (hex: string): number => {
      const rgb = this.hexToRgb(hex)
      if (!rgb) return 0

      const normalize = (color: number) => {
        const c = color / 255
        return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)
      }

      return 0.2126 * normalize(rgb.r) + 0.7152 * normalize(rgb.g) + 0.0722 * normalize(rgb.b)
    }

    const lum1 = getLuminance(color1)
    const lum2 = getLuminance(color2)
    const brightest = Math.max(lum1, lum2)
    const darkest = Math.min(lum1, lum2)

    return (brightest + 0.05) / (darkest + 0.05)
  }

  /**
   * 判断颜色是否为深色
   */
  static isDarkColor(hex: string): boolean {
    const rgb = this.hexToRgb(hex)
    if (!rgb) return false

    // 使用相对亮度公式
    const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000
    return brightness < 128
  }

  /**
   * 获取颜色的最佳文本颜色（黑色或白色）
   */
  static getBestTextColor(backgroundColor: string): string {
    return this.isDarkColor(backgroundColor) ? '#ffffff' : '#000000'
  }

  /**
   * 混合两种颜色
   */
  static mixColors(color1: string, color2: string, ratio: number = 0.5): string {
    const rgb1 = this.hexToRgb(color1)
    const rgb2 = this.hexToRgb(color2)
    
    if (!rgb1 || !rgb2) return color1

    const mix = (c1: number, c2: number) => Math.round(c1 * (1 - ratio) + c2 * ratio)

    return this.rgbToHex(
      mix(rgb1.r, rgb2.r),
      mix(rgb1.g, rgb2.g),
      mix(rgb1.b, rgb2.b)
    )
  }
}

// 响应式工具函数
export class ResponsiveUtils {
  /**
   * 获取当前屏幕断点（SSR 安全）
   */
  static getCurrentBreakpoint(): string {
    if (typeof window === 'undefined') return 'xl' // SSR 默认返回桌面断点

    const width = window.innerWidth

    if (width < 475) return 'xs'
    if (width < 640) return 'sm'
    if (width < 768) return 'md'
    if (width < 1024) return 'lg'
    if (width < 1280) return 'xl'
    return '2xl'
  }

  /**
   * 检查是否为移动设备（SSR 安全）
   */
  static isMobile(): boolean {
    if (typeof window === 'undefined') return false
    return window.innerWidth < 768
  }

  /**
   * 检查是否为平板设备（SSR 安全）
   */
  static isTablet(): boolean {
    if (typeof window === 'undefined') return false
    const width = window.innerWidth
    return width >= 768 && width < 1024
  }

  /**
   * 检查是否为桌面设备（SSR 安全）
   */
  static isDesktop(): boolean {
    if (typeof window === 'undefined') return true // SSR 默认为桌面
    return window.innerWidth >= 1024
  }

  /**
   * 监听屏幕尺寸变化（仅客户端）
   */
  static onBreakpointChange(callback: (breakpoint: string) => void): () => void {
    if (typeof window === 'undefined') {
      // SSR 环境返回空函数
      return () => {}
    }

    let currentBreakpoint = this.getCurrentBreakpoint()

    const handleResize = () => {
      const newBreakpoint = this.getCurrentBreakpoint()
      if (newBreakpoint !== currentBreakpoint) {
        currentBreakpoint = newBreakpoint
        callback(newBreakpoint)
      }
    }

    window.addEventListener('resize', handleResize)

    // 返回清理函数
    return () => {
      if (typeof window !== 'undefined') {
        window.removeEventListener('resize', handleResize)
      }
    }
  }
}

// 动画工具函数
export class AnimationUtils {
  /**
   * 缓动函数
   */
  static easing = {
    linear: (t: number) => t,
    easeInQuad: (t: number) => t * t,
    easeOutQuad: (t: number) => t * (2 - t),
    easeInOutQuad: (t: number) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
    easeInCubic: (t: number) => t * t * t,
    easeOutCubic: (t: number) => (--t) * t * t + 1,
    easeInOutCubic: (t: number) => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
  }

  /**
   * 数值动画（SSR 安全）
   */
  static animate(
    from: number,
    to: number,
    duration: number,
    callback: (value: number) => void,
    easing: (t: number) => number = this.easing.easeOutQuad
  ): () => void {
    // SSR 环境或浏览器不支持时，直接跳到目标值
    if (typeof window === 'undefined' || typeof requestAnimationFrame === 'undefined' || typeof performance === 'undefined') {
      callback(to)
      return () => {}
    }

    const startTime = performance.now()
    let animationId: number

    const step = (currentTime: number) => {
      const elapsed = currentTime - startTime
      const progress = Math.min(elapsed / duration, 1)
      const easedProgress = easing(progress)
      const currentValue = from + (to - from) * easedProgress

      callback(currentValue)

      if (progress < 1) {
        animationId = requestAnimationFrame(step)
      }
    }

    animationId = requestAnimationFrame(step)

    // 返回取消函数
    return () => {
      if (animationId) {
        cancelAnimationFrame(animationId)
      }
    }
  }

  /**
   * 滚动到指定位置（SSR 安全）
   */
  static scrollTo(
    element: HTMLElement | Window,
    to: number,
    duration: number = 300,
    easing: (t: number) => number = this.easing.easeOutQuad
  ): Promise<void> {
    return new Promise((resolve) => {
      if (typeof window === 'undefined') {
        resolve()
        return
      }

      const isWindow = element === window
      const from = isWindow ? window.pageYOffset : (element as HTMLElement).scrollTop

      this.animate(from, to, duration, (value) => {
        if (isWindow) {
          window.scrollTo(0, value)
        } else {
          (element as HTMLElement).scrollTop = value
        }
      }, easing)

      setTimeout(resolve, duration)
    })
  }
}

// 存储工具函数
export class StorageUtils {
  /**
   * 安全的 localStorage 操作（SSR 安全）
   */
  static setItem(key: string, value: any): boolean {
    if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
      return false
    }
    try {
      localStorage.setItem(key, JSON.stringify(value))
      return true
    } catch (error) {
      console.warn('Failed to save to localStorage:', error)
      return false
    }
  }

  static getItem<T>(key: string, defaultValue?: T): T | null {
    if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
      return defaultValue || null
    }
    try {
      const item = localStorage.getItem(key)
      return item ? JSON.parse(item) : defaultValue || null
    } catch (error) {
      console.warn('Failed to read from localStorage:', error)
      return defaultValue || null
    }
  }

  static removeItem(key: string): boolean {
    if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
      return false
    }
    try {
      localStorage.removeItem(key)
      return true
    } catch (error) {
      console.warn('Failed to remove from localStorage:', error)
      return false
    }
  }

  /**
   * 清理过期的存储项（SSR 安全）
   */
  static cleanExpired(): void {
    if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
      return
    }

    const now = Date.now()
    const keysToRemove: string[] = []

    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i)
      if (key && key.startsWith('officialblock-')) {
        try {
          const item = JSON.parse(localStorage.getItem(key) || '{}')
          if (item.expires && item.expires < now) {
            keysToRemove.push(key)
          }
        } catch (error) {
          // 忽略解析错误
        }
      }
    }

    keysToRemove.forEach(key => localStorage.removeItem(key))
  }
}

// 导出所有工具类
export default {
  ThemeUtils,
  ResponsiveUtils,
  AnimationUtils,
  StorageUtils
}
